//
//  WQEmojiKeyBoard.m
//  WQEmojiKeyboard
//
//  Created by Xiang on 2021/5/18.
//

#import "WQEmojiKeyBoard.h"
#import "EmotionTextAttachment.h"

@interface WQEmojiKeyBoard ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) UITextView *textView;

@property (nonatomic) NSMutableDictionary *emojiDic;

@property (nonatomic) NSArray *emojiImgArray;

@property (nonatomic) int location;

@end


@implementation WQEmojiKeyBoard

- (instancetype)initWithFrame:(CGRect)frame textView:(UITextView *)textView{
    if (self = [super init]) {
        self.frame = frame;
        self.textView = textView;
        [self initData];
        
        [self.collectionView registerClass:[WQEmojiItemCell class] forCellWithReuseIdentifier:@"WQEmojiItemCell"];
        
    }
    return self;
}

- (void)initData{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"emoji" ofType:@"json"];
    NSData *emojiData = [NSData dataWithContentsOfFile:path];
    NSError *Eerror;
    NSArray *classArray = [NSJSONSerialization JSONObjectWithData:emojiData options:NSJSONReadingAllowFragments error:&Eerror];
    NSMutableArray *tempArray = [NSMutableArray new];
    [tempArray addObjectsFromArray:classArray];
    self.emojiImgArray = tempArray;
    for (int i = 0; i < self.emojiImgArray.count; i++) {
        NSString *vall = self.emojiImgArray[i][@"img"];
        NSString *key = self.emojiImgArray[i][@"value"];
        [self.emojiDic setValue:vall forKey:key];
    }
}

- (UICollectionView *)collectionView{
    if (_collectionView == nil) {
        UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
        layout.minimumLineSpacing = 5;
        layout.minimumInteritemSpacing = 5;
        CGFloat width = (self.frame.size.width-20-35) / 8;
        CGFloat height = width;
        layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
        layout.itemSize = CGSizeMake((long)width, height);
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 250) collectionViewLayout:layout];
        [self addSubview:_collectionView];
        _collectionView.backgroundColor = UIColor.whiteColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.layer.zPosition = 1;
    }
    return _collectionView;
}

- (NSMutableDictionary *)emojiDic{
    if (_emojiDic == nil) {
        _emojiDic = [NSMutableDictionary new];
    }
    return _emojiDic;
}

- (void)setAttTextColor:(UIColor *)attTextColor{
    _attTextColor = attTextColor;
}

- (void)setAttTextFont:(UIFont *)attTextFont{
    _attTextFont = attTextFont;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.emojiImgArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    WQEmojiItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WQEmojiItemCell" forIndexPath:indexPath];
    cell.iconIv.image = [UIImage imageNamed:self.emojiImgArray[indexPath.item][@"img"]];
    return cell;
}

//要先设置表头高度（顶部内边距）
- (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    CGSize size = {self.frame.size.width, 15};
    return size;
}

//要先设置表尾高度（底部内边距）
- (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    CGSize size = {self.frame.size.width, 15};
    return size;
}

//表情按钮点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    

    NSString *value = self.emojiImgArray[indexPath.item][@"value"];
    NSString *img = self.emojiImgArray[indexPath.item][@"img"];
    
    NSMutableString *faceString = [[NSMutableString alloc]initWithString:self.textView.text];
    [faceString appendString:value];
    EmotionTextAttachment *emotionTextAttachment = [EmotionTextAttachment new];
    emotionTextAttachment.bounds = CGRectMake(0, -5.5, 21, 21);
    emotionTextAttachment.emotionStr = value;
    emotionTextAttachment.image = [UIImage imageNamed:img];
    self.location = (int)self.textView.selectedRange.location;
    [self.textView.textStorage insertAttributedString:[NSAttributedString attributedStringWithAttachment:emotionTextAttachment] atIndex:self.textView.selectedRange.location];
    [self.textView.textStorage addAttribute:NSForegroundColorAttributeName value:[UIColor darkGrayColor] range:NSMakeRange(0, self.textView.text.length)];
    [self.textView.textStorage addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, self.textView.text.length)];
    self.textView.selectedRange = NSMakeRange(self.location+1, 0);
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(emojiKeyBoard:emojiBtnClickForIndex:value:img:)]) {
        [self.delegate emojiKeyBoard:self emojiBtnClickForIndex:indexPath.item value:value img:img];
    }
    
}


- (void)keyBoardFrameChaneWithFrame:(CGRect)frame{
    self.collectionView.frame = CGRectMake(0, 0, frame.size.width, frame.size.height);
}

@end



@implementation WQEmojiItemCell

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self iconIv];
    }
    return self;
}

- (UIImageView *)iconIv{
    if (_iconIv == nil) {
        _iconIv = [[UIImageView alloc]init];
        [self.contentView addSubview:_iconIv];
        _iconIv.frame = CGRectMake(5, 5, self.frame.size.width-10, self.frame.size.height-10);
    }
    return _iconIv;
}


@end
